package com.demo.statemachine.demos.config;

import com.demo.statemachine.demos.event.OrderEvents;
import com.demo.statemachine.demos.state.OrderStates;
import org.springframework.context.annotation.Configuration;
import org.springframework.statemachine.action.Action;
import org.springframework.statemachine.config.EnableStateMachine;
import org.springframework.statemachine.config.StateMachineConfigurerAdapter;
import org.springframework.statemachine.config.builders.StateMachineStateConfigurer;
import org.springframework.statemachine.config.builders.StateMachineTransitionConfigurer;


@Configuration
@EnableStateMachine
public class StateMachineConfig extends StateMachineConfigurerAdapter<OrderStates, OrderEvents> {

    @Override
    public void configure(StateMachineStateConfigurer<OrderStates, OrderEvents> states) throws Exception {
        states
            .withStates()
            .initial(OrderStates.WAITING_FOR_REVIEW)
            .state(OrderStates.UNDER_REVIEW)
            .end(OrderStates.APPROVED)
            .end(OrderStates.REJECTED);
    }

    @Override
    public void configure(StateMachineTransitionConfigurer<OrderStates, OrderEvents> transitions) throws Exception {
        transitions
            .withExternal()
                .source(OrderStates.WAITING_FOR_REVIEW).target(OrderStates.UNDER_REVIEW).event(OrderEvents.START_REVIEW).action(doNoting())
            .and()
            .withExternal()
                .source(OrderStates.UNDER_REVIEW).target(OrderStates.APPROVED).event(OrderEvents.APPROVE).action(sendMessageAction())
            .and()
            .withExternal()
                .source(OrderStates.UNDER_REVIEW).target(OrderStates.REJECTED).event(OrderEvents.REJECT).action(sendMessageAction());
    }

    public Action<OrderStates, OrderEvents> sendMessageAction() {
        return context -> {
            // 假设发起审核人的ID存在上下文中，可以从context中获取
            String userId = (String) context.getExtendedState().getVariables().get("userId");
            // 执行发送消息的逻辑
            System.out.println("Sending message to user: " + userId);
        };
    }

    public Action<OrderStates, OrderEvents> doNoting() {
        return context -> {
            // 假设发起审核人的ID存在上下文中，可以从context中获取
            String userId = (String) context.getExtendedState().getVariables().get("userId");
            // 执行发送消息的逻辑
            System.out.println("Sending message to user: " + userId);
        };
    }
}
